import React, {memo, useEffect, useMemo, useState} from 'react'
import {Radio, Button, Space} from 'antd'
import {
	PlusOutlined,
	ArrowDownOutlined,
	ArrowUpOutlined,
} from '@ant-design/icons'
import {connect, history} from 'umi'
import type {ColumnsType} from 'antd/es/table'
import {getAllCitys, getCompany} from '@/service/common/index'
import {
	getErrorListPage,
	getImportData,
	getTableList,
} from '@/service/customer/driver'
import {translateDataToTree} from '@/utils/common/index'
import {getDict} from '@/service/common/dict'
import SearchForm from '@/components/SearchForm'
import CustomTable from '@/components/Table'
import Permissions from '@/components/Permissions'
import {SoundEnum, SoundMap, DirverClounm} from '../constant'
import styles from './index.less'
import BatchUpload from '@/components/BatchUpload'
import {modalApi} from '@/utils/modalReq'
// import {formItemType} from '../../fleet/constant'
import {downloadDocumentUrl} from '@/service/common/download'

interface CityOption {
	value: string | number
	label: string
	children?: CityOption[]
}

interface DataType {
	name: string
	tel: string
	idNo: string
	reason: string
}

const List = memo((props: any) => {
	// const [searchValue, setSearchValue] = useState({})
	const [tabValue, setTabValue] = useState(SoundEnum.yes)
	const [citysList, setCitysList] = useState<CityOption[]>([])
	const [companyData, setCompanyData] = useState<any[]>([])
	const [yesSoundLst, setYesSoundList] = useState<any[]>([])
	const [noSoundList, setNoSoundList] = useState<any[]>([])
	const [tableLoading, setTableLoading] = useState(false)
	const [yesTotal, setYesTotal] = useState(0)
	const [yesPagination, setYesPagination] = useState({
		current: 1,
		size: 10,
	})
	const [noTotal, setNoTotal] = useState(0)
	const [noPagination, setNoPagination] = useState({
		current: 1,
		size: 10,
	})
	const [searchValue, setSearchValue] = useState<any>({})
	const [dict, setDict] = useState({
		yes_no: [],
		driver_channel_source: [],
		driver_status: [],
	})
	const [isUploadModalOpen, setIsUploadModalOpen] = useState(false)
	const {query} = props?.location || {}

	const getData = async (params?: Record<string, any>): Promise<any> => {
		history.push(`/driver/list?type=${tabValue}`)
		const obj = {...searchValue, ...params}
		obj.isDdOrder = tabValue === SoundEnum.yes ? '0' : '1'
		setTableLoading(true)
		const data = await getTableList({
			...obj,
			current:
				tabValue === SoundEnum.yes
					? yesPagination.current
					: noPagination.current,
			size:
				tabValue === SoundEnum.yes
					? yesPagination.size
					: noPagination.size,
		}).catch(() => {
			setTableLoading(false)
		})
		if (data.code === 0) {
			setYesSoundList(data.data.records)
			if (tabValue === SoundEnum.yes) {
				setYesTotal(data.data.total)
			} else {
				setNoSoundList(data.data.records)
				setNoTotal(data.data.total)
			}
		}
		setTableLoading(false)
	}

	// 初始化-城市
	const getCitysFun = () => {
		getAllCitys().then((res: any) => {
			if (res?.data) {
				setCitysList(() => res.data || [])
			}
		})
	}

	/** 获取所属公司数据 */
	const onCompany = () => {
		getCompany({merchantId: props?.user?.orgId}).then((res: any) => {
			if (res?.success) {
				const list = translateDataToTree(res.data)
				setCompanyData(list as any)
			}
		})
	}

	useEffect(() => {
		getCitysFun()
		onCompany()
		getDict(
			{
				dictKeys: ['yes_no', 'driver_channel_source', 'driver_status'],
			},
			(res: any) => {
				setDict(res)
			},
		)
	}, [])

	useEffect(() => {
		if (query?.type) {
			setTabValue(Number(query?.type))
		}
	}, [])

	useEffect(() => {
		getData()
	}, [tabValue, yesPagination, noPagination])

	const FormItems: any[] = [
		{
			type: 'group',
			key: 'group1',
			groupItems: [
				{
					type: 'treeSelect',
					label: '司机所属公司',
					name: 'groupOrgId',
					key: 'groupOrgId',
					placeholder: '请选择',
					treeData: companyData,
					title: 'name',
					keys: 'id',
					defaultExpandAll: true,
				},
				{
					type: 'cascader',
					label: '城市',
					name: 'cityId',
					key: 'cityId',
					placeholder: '请选择',
					items: citysList,
					fieldNames: {
						label: 'name',
						value: 'id',
						children: 'cityInfoList',
					},
				},
				{
					type: 'input',
					key: 'expressId',
					name: 'expressId',
					label: '司机ID',
					keys: 'value',
					title: 'title',
				},
			],
		},

		{
			type: 'group',
			key: 'group3',
			groupItems: [
				{
					type: 'input',
					label: '司机姓名',
					name: 'name',
					key: 'name',
				},
				{
					type: 'select',
					label: '司机状态',
					name: 'status',
					key: 'status',
					items: dict.driver_status.map((item: any) => ({
						label: item.dictValue,
						value: item.dictKey,
					})),
				},
				{
					type: 'input',
					label: '司机标签',
					name: 'tag',
					key: 'tag',
				},
			],
		},
		{
			type: 'group',
			key: 'group2',
			groupItems: [
				{
					type: 'select',
					label: '司机渠道来源',
					name: 'uSource',
					key: 'uSource',
					placeholder: '请选择',
					items: dict.driver_channel_source.map((item: any) => ({
						label: item.dictValue,
						value: item.dictKey,
					})),
				},
				// {
				// 	type: 'input',
				// 	key: 'ditchCode',
				// 	name: 'ditchCode',
				// 	label: '司机渠道代码',
				// 	keys: 'value',
				// 	title: 'title',
				// },
				{
					type: 'input',
					key: 'carLeader',
					name: 'carLeader',
					label: '车队长',
					keys: 'value',
					title: 'title',
				},
				{},
			],
		},
	]

	// 打开详情
	const openDetail = (record: Record<string, string>) => {
		history.push({
			pathname: '/driver/detail',
			query: {
				id: record.driverId,
				orgId: record.groupOrgId,
				status: record.status,
				type: 'detail',
			},
		})
	}

	// 打开编辑
	const openEditPage = (record: Record<string, string>) => {
		history.push({
			pathname: '/driver/edit',
			query: {
				type: 'edit',
				id: record.driverId,
				orgId: record.groupOrgId,
				status: record.status,
			},
		})
	}

	const getTableClounms = useMemo(
		() => [
			...DirverClounm,
			{
				title: '操作',
				dataIndex: '',
				fixed: 'right',
				width: 120,
				render: (ffield: string, record: Record<string, any>) => (
					<Space size={12}>
						<Permissions permissionID="amc_customer_driver_list_review">
							<Button
								type="link"
								onClick={() => openDetail(record)}>
								查看
							</Button>
						</Permissions>
						<Permissions permissionID="amc_customer_driver_list_edit">
							<Button
								type="link"
								onClick={() => openEditPage(record)}>
								编辑
							</Button>
						</Permissions>
					</Space>
				),
			},
		],
		[],
	)

	const errorColumns: ColumnsType<DataType> = [
		{
			title: '司机姓名',
			dataIndex: 'name',
			align: 'center',
			width: 120,
		},
		{
			title: '司机手机号',
			dataIndex: 'tel',
			align: 'center',
			width: 120,
		},
		{
			title: '司机身份证号',
			dataIndex: 'idNo',
			align: 'center',
			width: 140,
		},
		{
			title: '失败原因',
			dataIndex: 'reason',
			align: 'center',
			width: 140,
		},
	]

	const onExportClick = () => {
		downloadDocumentUrl({
			resourceId: '101',
			queryDesc:
				'fleetName:车队名称,captainName:车队长名称,captainPhone:车队长电话',
			queryParam: {
				...searchValue,
				isDdOrder: tabValue === SoundEnum.yes ? '0' : '1',
			},
		})
	}
	return (
		<div className={styles.drivr}>
			<div className={styles.searchBox}>
				<SearchForm
					formLayout={{
						labelCol: {flex: '110px'},
						wrapperCol: {flex: '1'},
					}}
					formItems={FormItems}
					onReset={async () => {
						setSearchValue({})
						const data = await getTableList({
							isDdOrder: tabValue === SoundEnum.yes ? '0' : '1',
							current: 1,
							size:
								tabValue === SoundEnum.yes
									? yesPagination.size
									: noPagination.size,
						}).catch(() => {
							setTableLoading(false)
						})
						if (data.code === 0) {
							setYesSoundList(data.data.records)
							if (tabValue === SoundEnum.yes) {
								setYesTotal(data.data.total)
								setYesPagination({
									current: 1,
									size: yesPagination.size,
								})
							} else {
								setNoSoundList(data.data.records)
								setNoPagination({
									current: 1,
									size: noPagination.size,
								})
								setNoTotal(data.data.total)
							}
						}
						setTableLoading(false)
					}}
					onFinish={async (value) => {
						const obj = {...value}
						obj.cityId = obj.cityId
							? obj.cityId[obj.cityId.length - 1]
							: undefined
						setSearchValue(obj)
						history.push(`/driver/list?type=${tabValue}`)
						obj.isDdOrder = tabValue === SoundEnum.yes ? '0' : '1'
						setTableLoading(true)
						const data = await getTableList({
							...obj,
							current: 1,
							size:
								tabValue === SoundEnum.yes
									? yesPagination.size
									: noPagination.size,
						}).catch(() => {
							setTableLoading(false)
						})
						if (data.code === 0) {
							setYesSoundList(data.data.records)
							if (tabValue === SoundEnum.yes) {
								setYesTotal(data.data.total)
								setYesPagination({
									current: 1,
									size: yesPagination.size,
								})
							} else {
								setNoSoundList(data.data.records)
								setNoPagination({
									current: 1,
									size: noPagination.size,
								})
								setNoTotal(data.data.total)
							}
						}
						setTableLoading(false)
					}}
				/>
			</div>
			<div className={styles.tableBox}>
				<div className={styles.btnBox}>
					<Radio.Group
						value={tabValue}
						onChange={(e) => {
							setTabValue(e.target.value)
						}}>
						<Radio.Button value={SoundEnum.yes}>
							{SoundMap[SoundEnum.yes]}
						</Radio.Button>
						<Radio.Button value={SoundEnum.no}>
							{SoundMap[SoundEnum.no]}
						</Radio.Button>
					</Radio.Group>
					<div>
						<Space size={12}>
							<Permissions permissionID="amc_customer_driver_list_add">
								<Button
									icon={<PlusOutlined />}
									type="primary"
									ghost
									size="small"
									onClick={() => {
										history.push({
											pathname: '/driver/add',
											query: {
												type: 'add',
												dirver:
													tabValue === SoundEnum.yes
														? '2'
														: '1',
											},
										})
									}}>
									新增
								</Button>
							</Permissions>
							<Permissions permissionID="amc_customer_driver_list_import">
								<Button
									icon={<ArrowUpOutlined />}
									className={styles.warning}
									ghost
									size="small"
									onClick={() => setIsUploadModalOpen(true)}>
									导入
								</Button>
							</Permissions>
							<Permissions permissionID="amc_customer_driver_list_export">
								<Button
									icon={<ArrowDownOutlined />}
									className={styles.import}
									ghost
									size="small"
									onClick={onExportClick}>
									导出
								</Button>
							</Permissions>
						</Space>
					</div>
				</div>
				<div className={styles.content}>
					{tabValue === SoundEnum.yes ? (
						<CustomTable
							pagination
							params={yesPagination}
							total={yesTotal}
							columns={getTableClounms}
							callback={(pagination: any) => {
								setYesPagination(pagination)
							}}
							dataSource={yesSoundLst}
							loading={tableLoading}
						/>
					) : (
						<CustomTable
							pagination
							params={noPagination}
							total={noTotal}
							columns={getTableClounms}
							callback={(pagination: any) => {
								setNoPagination(pagination)
							}}
							dataSource={noSoundList}
							loading={tableLoading}
						/>
					)}
				</div>
			</div>
			<BatchUpload
				isModalOpen={isUploadModalOpen}
				setIsModalOpen={setIsUploadModalOpen}
				importData={getImportData}
				onTableList={getErrorListPage}
				getListData={getData}
				uploadFileUrl={`${modalApi.customer}/drivers/import/check`}
				columns={errorColumns}
				sourceId={11}
				templateType="司机导入"
			/>
		</div>
	)
})

export default connect(({user}: any) => ({user}))(List)
